package com.wx.utils.pay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import com.alibaba.fastjson.JSONObject;

public class HttpRequest {
	//连接超时时间，默认10秒
    private static final int socketTimeout = 10000;

    //传输超时时间，默认30秒
    private static final int connectTimeout = 30000;
	/**
	 * post请求
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyStoreException 
	 * @throws KeyManagementException 
	 * @throws UnrecoverableKeyException 
	 */
	/*public static String sendPost(String url, Object xmlObj) throws ClientProtocolException, IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
		
	
	    
		HttpPost httpPost = new HttpPost(url);
		//解决XStream对出现双下划线的bug
	    XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
	    xStreamForRequestPostData.alias("xml", xmlObj.getClass());
	    //将要提交给API的数据对象转换成XML格式数据Post给API
	    String postDataXML = xStreamForRequestPostData.toXML(xmlObj);
	
	    //得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
	    StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
	    httpPost.addHeader("Content-Type", "text/xml");
	    httpPost.setEntity(postEntity);
	
	    //设置请求器的配置
	    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
	    httpPost.setConfig(requestConfig);
	    
	    HttpClient httpClient = HttpClients.createDefault();
	    HttpResponse response = httpClient.execute(httpPost);
	    HttpEntity entity = response.getEntity();
	    String result = EntityUtils.toString(entity, "UTF-8");
	    return result;
	}*/
	
	public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            //for (String key : map.keySet()) {
                //System.out.println(key + "--->" + map.get(key));
            //}
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            //System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
	
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;

    }
	
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {

		JSONObject jsonObject = null;

		StringBuffer buffer = new StringBuffer();

		try {

		// 创建SSLContext对象，并使用我们指定的信任管理器初始化

		TrustManager[] tm = { new MyX509TrustManager() };

		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

		sslContext.init(null, tm, new java.security.SecureRandom());

		// 从上述SSLContext对象中得到SSLSocketFactory对象

		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL url = new URL(requestUrl);

		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();

		httpUrlConn.setSSLSocketFactory(ssf);

		httpUrlConn.setDoOutput(true);

		httpUrlConn.setDoInput(true);

		httpUrlConn.setUseCaches(false);

		// 设置请求方式（GET/POST）

		httpUrlConn.setRequestMethod(requestMethod);

		if ("GET".equalsIgnoreCase(requestMethod))

		httpUrlConn.connect();

		// 当有数据需要提交时

		if (null != outputStr) {

		OutputStream outputStream = httpUrlConn.getOutputStream();

		// 注意编码格式，防止中文乱码

		outputStream.write(outputStr.getBytes("UTF-8"));

		outputStream.close();

		}

		// 将返回的输入流转换成字符串

		InputStream inputStream = httpUrlConn.getInputStream();

		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");

		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

		String str = null;

		while ((str = bufferedReader.readLine()) != null) {

		buffer.append(str);

		}

		bufferedReader.close();

		inputStreamReader.close();

		// 释放资源

		inputStream.close();

		inputStream = null;

		httpUrlConn.disconnect();

		jsonObject = JSONObject.parseObject(buffer.toString());

		} catch (ConnectException ce) {

		ce.printStackTrace();

		} catch (Exception e) {

		e.printStackTrace();

		}

		return jsonObject;

		}
	
	/**
	 * 自定义证书管理器，信任所有证书
	 * @author pc
	 *
	 */
	public static class MyX509TrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
			// TODO Auto-generated method stub
			
		}
		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
      }

	public static String doGet(String string, Map<String, String> map) {
		// TODO Auto-generated method stub
		return null;
	}
}
